<?php
namespace app\api\controller;
use app\common\controller\Api;

/**
 * 获取OSS服务端签名类
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/10
 * Time: 14:31
 */
class OssClient extends Api
{
    protected $noNeedLogin = ['*'];

    private $accessKeyId = 'LTAI5tN8YApuuW5NEi9LDbwr';
    private $accessKeySecret = 'rit7irfyfB8zGUXwRtH94kPJBOvp41';
    private $host = 'tiktoks-video.oss-cn-beijing.aliyuncs.com';
    private $callbackUrl = 'http://dy.mt.com/callback.php';
    /**
     * 获取OSS应用服务端签名
     * @param (string)$dir : 上传到OSS的文件路径 如文件权路径为 image/001.png  那么 $dir = 'image/';  即可
     */
    public function getOssSignature()
    {
        $id = $this->accessKeyId;
        $key = $this->accessKeySecret;
        $host = $this->host;
        $callbackUrl = $this->callbackUrl;

        $callback_param = array('callbackUrl' => $callbackUrl,
            'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType' => "application/x-www-form-urlencoded");
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30;
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);


        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition;


        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;

        $res =  [
            'code' => 0,
            'success' => true,
            'msg' => 'success',
            'data' => $response
        ];

        return json($res);
    }

    private function gmt_iso8601($time)
    {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration . "Z";
    }
}


?>

